/**
 *
 * 用户登录接口
 *
 */
const rootPath = '../../../';
const router = require('express').Router();
const baseTool = require(rootPath + 'common/base-tool');
const baseRole = require(rootPath + 'common/base-role');
const tips = require(rootPath + 'common/tips');
const log = require(rootPath + 'common/log');
const CURD = require(rootPath + 'compontents/DB/CURDClass')
const RSA = require(rootPath + 'common/RSAClass');
const md5 = require('md5-node');
const expressWs = require('express-ws');
expressWs(router);

router.post('/login', async (req, res, next) => {
    log.api('user login');

    /**
     * =======================
     *   自动登录
     * =======================
     */
    let xhtk = req.cookies.xhtk;
    let uid = req.cookies.uid;
    if (xhtk && uid) {
        // 解密
        try {
            xhtk = await new RSA().decrypt(xhtk);

            // token有误
            if (xhtk == tips.loginCookie.failCode) {
                res.clearCookie('xhtk')
                res.clearCookie('uid')
                res.json({
                    code: tips.loginCookie.failCode,
                    msg: tips.loginCookie.fail
                })
                return;
            }

            const token = xhtk.split('_XHPX_')[1];
            const login_rows = await CURD.select({
                fields: '`ename`',
                table: 'user',
                where: [{wfield: 'uid', wvalue: uid}, {wfield: 'token', wvalue: token}]
            });
            if (login_rows.length) {
                // 数据处理
                dataHandle(res, login_rows[0].ename, uid)
            } else {
                res.cookie('uid', 0, {signed: false, maxAge: 0});
                res.cookie('xhtk', 0, {signed: false, httpOnly: true, maxAge: 0});
                res.json({
                    code: tips.loginCookie.failCode,
                    msg: tips.loginCookie.fail
                })
            }
        } catch (err) {
            log.err(err);
        }
        return;
    }

    const r = req.body;
    const uname = r.uname;
    const password = r.pwd;

    // 账号、密码格式验证
    if (!uname) {
        res.json({
            code: tips.uname.emptyCode,
            msg: tips.uname.emport
        })
        return;
    }
    if (!password) {
        res.json({
            code: tips.pwd.emptyCode,
            msg: tips.pwd.emport
        })
        return;
    }
    if (!baseTool.verifyName(uname)) {
        console.log(tips.uname.format);
        res.json({
            code: tips.uname.formatCode,
            msg: tips.uname.format
        })
        return;
    }

    if (!baseTool.verifyPwd(password)) {
        res.json({
            code: tips.pwd.formatCode,
            msg: tips.pwd.format
        })
        return;
    }


    /**
     * =======================
     *   账号密码登录
     * =======================
     */
    try {
        const login_rows = await CURD.select({
            fields: '`uid`, `ename`, `token`',
            table: 'user',
            where: [{wfield: 'ename', wvalue: uname}, {wfield: 'password', wvalue: md5(password)}]
        })

        if (login_rows.length) {
            const rows = login_rows[0]

            // 公钥加密
            const t = rows.id +'_XHPX_'+ rows.token.toString();
            const publicKey = await new RSA().encrypt(t);

            //创建cookie对象
            res.cookie('uid', rows.uid, {signed: false, maxAge: global.COOKIE_TIME});
            res.cookie('xhtk', publicKey, {signed: false, httpOnly: true, maxAge: global.COOKIE_TIME});

            // 吐出数据
            dataHandle(res, rows.ename, rows.uid)
        } else {
            res.send({
                code:tips.login.failCode,
                msg:tips.login.fail,
                ename:ename
            })
        }
    } catch (e) {
        console.log(e)
        res.json({
            code: tips.sql.selectFailCode,
            msg: tips.sql.selectFail
        })
    }
})

module.exports = router;

// 数据处理
function dataHandle (res, ename, uid) {
    // 是否已注册
    baseRole.get_user_info(uid).then( hasInfo => {
        console.log(hasInfo)
        if (hasInfo > 0) {
            // 某房间是否有该角色
            baseRole.get_online_list(hasInfo, uid, ename).then((list) => {

                // uid数据拼装
                baseRole.room_data_handle(list, uid, ename, hasInfo).then(result => {

                    // // 把该房间角色数据添加到全局变量
                    // global.ROOM_ROLE_LISTS.push(result.room_data);
                    //
                    // // 原数组：去重
                    // const rList = global.ROOM_ROLE_LISTS;
                    // for (var i in rList) {
                    //     if (rList[i].room == list.room) {
                    //         // 删除原数据
                    //         global.ROOM_ROLE_LISTS = rList.splice(rList.indexOf(i), 1)
                    //         continue;
                    //     }
                    // }

                    // 吐出数据
                    spitOutData(res, result.hasInfo, ename, uid)
                });
            });
        } else {
            // 吐出数据
            spitOutData(res, -1, ename, uid)
        }
    })
}

// 吐出数据
/**
 *
 * @param res
 * @param hasInfo
 *     // -1, 无角色信息
 *     // 0, 有角色信息，请设置天赋
 *     // 1, 有天赋，选择性格
 *     // 2, 已出生，在新手村
 *     // 3, 出新手村
 * @param ename
 * @param uid
 */
function spitOutData(res, hasInfo, ename, uid) {
    if (hasInfo > -1) {
        // 有角色信息
        console.log('有角色信息')
        let resData = {
            code: tips.successCode,
            msg: tips.success,
            ename: ename,
            status: hasInfo
        };
        res.json(resData)
    } else {
        // 无角色信息
        console.log('无角色信息')
        res.json({
            code: tips.successCode,
            msg: tips.success,
            ename: ename,
            status: 0
        });
    }
}

